angular.module("app").component("winitPrototypePanel", {
    templateUrl: getTemplateUrl("matrix/component/tpl/winitPrototypePanel.html"),
    bindings: {
        reqId: "<",
        featureId: "<",
        sys: "=",
        selectedBranch: "=",
        readonly: "<",
        mid     : '<',
        featureIndex: '@',
        isFile: '<',
        panelType: "@",    //true：功能树   false：编辑页面
        isMaster: '<',  // 是否是mster
        prevData        : "<",    //比较数据一
        nextData        : "<"     //比较数据二
    },
    controller: function ($scope, $rootScope, $stateParams, $http, $timeout, lodash) {
        var self = this;
        $scope.genreType = self.mid ? (self.mid +"chartlet") : (self.featureId +"chartlet");
        $scope.showIframe = false;
        $scope.scale = 1;
        $scope.transValue = "";
        $scope.featureId = "";
        $scope.isAxure = "chartlet";
        $scope.colFrameId = "";
        $scope.isOnline = false; //true：线上需求   false：当前需求
        $scope.prototypeContent = {
            prototype: "",
            version: "",
            master_version: "",
            req_snapshot: "",
            form: "",
            view: ""
        };   //原型内容
        $scope.master = {
            prototype: "",
            version: "",
            master_version: "",
            req_snapshot: "",
            form: "",
            view: ""
        };
        $scope.initPrototype = {
            prototype: "",
            version: "",
            master_version: "",
            req_snapshot: "",
            form: "",
            view: ""
        };
        $scope.prototypeContentMaster = {
            prototype: "",
            version: "",
            master_version: "",
            req_snapshot: "",
            form: "",
            view: ""
        };
        $scope.prototypeContentReq = {
            prototype: "",
            version: "",
            master_version: "",
            req_snapshot: "",
            form: "",
            view: ""
        };
        $scope.showPrototypePanel = true;
        $scope.nodePath = "";
        $scope.changeHeight = true;
        $scope.showSwitch = false;
        $scope.editHtml = false;   //true：可以编辑内容  false：不可以
        $scope.classStyle = "panel panel-info";
        $scope.wsying = {};
        $scope.transformTypeForm = "text";
        $scope.transformTypeView = "text";
        $scope.prototypeType = self.mid ? (self.mid +"current") : (self.featureId +"current");
        $scope.feaId = self.mid ? self.mid : self.featureId;
        $scope.isCompare = false;
        $scope.requestTwo = false;
        $scope.onlineIframe = false;

        $scope.info = {
            expression      : "",
            tableContent    : "table\n[],出口报关指令单号|l,出口报关服务单号|l|u,物流单号\n[],CK01000184879,D010101000040946,C030101000027326\n[], CK01000184879,D010101000040946,C030101000027326\nEnd\n",
            tabTableContent : "tab-table\n全部,等待清关|v,清关完成--创建\n[],出口报关指令单号|l,出口报关服务单号|l|u,物流单号\n[],CK01000184879,D010101000040946,C030101000027326,\n[],CK01000184879,D010101000040946,C030101000027326\nEnd\n",
            formContent     : "form\ncombo-select:派送指令单/xxx指令单|u\nselect:是否异常,请选择/是/否\ninput:客户\ndate:日期*;必须输入,日期小于当天\ndate-to: 起止\ncustomer:某控件,请参考原型\nsearch-button:查询\nEnd\n",
            textFormContent : "text-form\nname*,文本框;info1/info2/info3|u\nname*,文本框;info1/info2/info3\nname*,文本框;info1/info2/info3\nEnd\n",
            flowContent     : "flow\n1111|u\n222\n333\nEnd\n",
            comboContent    : "form\ncombo-select:关键字/Winit订单号|u\nselect:是否异常,请选择/是/否\ndate-to: 提交时间\nselect:状态,请选择/已下单/已到仓/已出库/作废\nselect:验货仓,请选择/深圳仓/UK Warehouse/海南(ZT仓)/香港ISP仓\nselect:目的仓,请选择/深圳仓/UK Warehouse/海南(ZT仓)/香港ISP仓\nselect:Winit产品,请选择/空运电商清关/空运定制渠道\nselect:验货方式,请选择/自验货/验货仓验货\nsearch-button:查询\nEnd\ntab-table\n全部订单|v,已下单,已收货,运输中,已到仓,已上架,异常订单,作废,中止--创建\n[],状态,Winit订单号|l|u,客户,Winit产品,验货方式,包裹数,是否异常,操作|l\n[],已收货,W1900XXX,Winit(UK),海运整柜-40GP,验货仓验货,8,否,查看,\n[],运输中,W1900XXX,Winit(UK),空运-普货,验货仓验货,8,否,查看,\n[],已下单,W1900XXX,Winit(UK),海运整柜-20GP-电商清关,验货仓验货,8,否,查看,\n[],已上架,W1900XXX,Winit(UK),海运整柜-40GP,验货仓验货,8,否,查看,\n[],已到仓,W1900XXX,Winit(UK),空运-普货,验货仓验货,8,否,查看,\nEnd\n",
        };
        $scope.isSave = false;
        $scope.selectedItem = "default";

        $scope.setTableHeight = function () {
            $timeout(function () {
                var h = document.documentElement.clientHeight || document.body.clientHeight;
                h = h - 300;
                if (document.getElementById("panelTextarea")) {
                    document.getElementById("panelTextarea").style.height = h + "px";
                }
                if (document.getElementById("panelTextarea2")) {
                    document.getElementById("panelTextarea2").style.height = h + "px";
                }
            })
        }
        if(self.isMaster) {
            $scope.setTableHeight();
            window.onresize = $scope.setTableHeight;
        }

        self.$onChanges = function (data) {
            $rootScope.showPanelLoading();
            $scope.isReadOnly = self.readonly;
            $scope.featureId = self.mid ? self.mid : self.featureId;
            $scope.isMaster = $stateParams.reqId == "-1" ? true : false;
            //功能树
            if (self.panelType == "tree") {
                if ($stateParams.reqId == "-1") {
                    //-1功能树
                    $scope.showSwitch = false;
                    $scope.classStyle = "panel panel-info";
                    $scope.showEditTitle = false;
                    $scope.showUsedTitle = false;
                    $scope.editHtml = true;
                } else {
                    if (self.reqId == "-1") {
                        //state有值，self等于-1
                        $scope.showSwitch = false;
                        $scope.classStyle = "panel panel-info";
                        $scope.showEditTitle = true;
                        $scope.showUsedTitle = false;
                        $scope.editHtml = false;
                    } else if (self.reqId != "-1" && self.reqId != $stateParams.reqId) {
                        $scope.showSwitch = false;
                        $scope.classStyle = "panel panel-warning";
                        $scope.showEditTitle = false;
                        $scope.showUsedTitle = true;
                        $scope.editHtml = false;
                    } else if (self.reqId == $stateParams.reqId) {
                        $scope.showSwitch = true;
                        $scope.classStyle = "panel panel-info";
                        $scope.showEditTitle = false;
                        $scope.showUsedTitle = false;
                        $scope.editHtml = true;
                    }
                }
            } else {
                $scope.showSwitch = true;
                $scope.editHtml = true;
                if(self.prevData || self.nextData){
                    $scope.isCompare=true;
                    $scope.prototypeContent=self.prevData;
                    $scope.prototypeContentMaster=self.nextData
                }
            }
            var currentReqId = $stateParams.reqId == undefined ? self.reqId : $stateParams.reqId;
            getFeaturesByReqId();
            if(!$scope.requestTwo) {
                getPrototypeByReq(false, currentReqId);
            }
            if(!data.reqId) {
                $scope.prototypeType = self.mid ? (self.mid +"current") : (self.featureId +"current");
                getPrototypeByReq(false, $stateParams.reqId);
            }
            $rootScope.hidePanelLoading();
        };

        function getPrototypeByReq(checked, reqId, isAxure) {
            $scope.requestTwo = true;
            $scope.isOnline = checked;
            //判断当前节点是否是req节点（menu,page节点没有reqId）
            if (!self.reqId) {
                return false;
            }
            $rootScope.showPanelLoading();
            var url = matrix_product_url + "/feature/getFeature?id=" + self.featureId + "&reqId=" + reqId + "&withAttr=1";
            if (self.sys) {
                url = url + "&sys=" + self.sys;
            }
            $.ajax({
                type: "get",
                url: url,
                async: false,
                success: function (result) {
                    if (result.code == "0") {
                        if (result.data == null) {
                            $rootScope.showMessage("error", "失败", "获取原型数据失败！");
                            $scope.showPrototypePanel = false;
                            $scope.nodePath = "";
                            $rootScope.hidePanelLoading();
                            return false;
                        } else {
                            $scope.showPrototypePanel = true;
                        }
                        if (result.data[0].attr != null) {
                            $scope.changeHeight = result.data[0].attr.prototype == "" ? true : false;
                            if (result.data[0].attr.req_snapshot != "") {
                                if (result.data[0].attr.req_snapshot == $stateParams.reqId) {
                                    $scope.showUsedTitle = true;
                                }
                            }
                            if (self.reqId != "-1" && self.reqId != undefined) {
                                getReqName();
                            }
                        }
                        $scope.$broadcast("to-wsying", result.data[0].attr);
                        var attrData = {
                            prototype: "",
                            form: "",
                            view: ""
                        };

                        $scope.prototypeContent = result.data[0].attr ? result.data[0].attr : attrData;
                        $scope.prototypeContentReq = result.data[0].attr ? result.data[0].attr : attrData;
                        if ($scope.prototypeContent.form) {
                            if ($scope.prototypeContent.form.split("|")[1]) {
                                $scope.transformTypeForm = $scope.prototypeContent.form.split("|")[0];
                            } else {
                                $scope.transformTypeForm = "text";
                            }
                        }
                        if ($scope.prototypeContent.view) {
                            var splitByEnd = $scope.prototypeContent.view.split("End\n");
                            var resultArray = [];
                            angular.forEach(splitByEnd, function (trans, index) {
                                var currentType = trans.split("\n")[0];
                                if (currentType != "tab-table" && currentType != "form" && currentType != "text-form" && currentType != "flow" && currentType != "table") {
                                    currentType = "other";
                                }
                                resultArray.push({"type": currentType, "data": trans});
                            });
                            $scope.transValue = resultArray;
                            if ($scope.prototypeContent.view.split("\n")[1]) {
                                $scope.transformTypeView = "data";
                            } else {
                                $scope.transformTypeView = "text";
                            }
                        } else {
                            $scope.transformTypeView = "text";
                        }
                        $scope.initPrototype = result.data[0].attr != null ? angular.copy(result.data[0].attr) : attrData;
                        $scope.nodePath = result.data[0].path + "/页面";
                        $scope.$broadcast('getWsyingFun', '');
                    } else {
                        $rootScope.showMessage("error", "失败", result.desc);
                    }
                    if(result.data[0].attr != null) {
                        //设置默认选择贴图,axure
                        if(result.data[0].attr.patternType == "axure") {
                            if(isAxure != true) {
                                $scope.genreType = self.mid ? (self.mid +"axure") : (self.featureId +"axure");
                                $scope.isAxure = "axure";
                            }
                            if ($scope.prototypeContent.prototype_file_path) {
                                var feaId = self.mid ? self.mid : self.featureId;
                                $("#"+ feaId +"iframepage").remove();
                                setIframe($scope.prototypeContent.prototype_file_path, feaId);
                            }
                        }
                        if(result.data[0].attr.patternType == undefined || result.data[0].attr.patternType == "doc") {
                            $scope.isAxure = "chartlet";
                            $scope.genreType = self.mid ? (self.mid +"chartlet") : (self.featureId +"chartlet");
                        }
                        if(result.data[0].attr.patternType == "expression") {
                            $scope.isAxure = "expression";
                            $scope.genreType = self.mid ? (self.mid +"expression") : (self.featureId +"expression");
                            $scope.isSave = true;
                            $scope.info.expression = result.data[0].attr.expression;
                            var splitByEnd = $scope.info.expression.split("End\n");
                            var resultArray = [];
                            angular.forEach(splitByEnd, function (trans, index) {
                                var currentType = lodash.trim(trans.split("\n")[0]);
                                if (currentType != "tab-table" && currentType != "form" && currentType != "text-form" && currentType != "flow" && currentType != "table") {
                                    currentType = "other";
                                }
                                resultArray.push({"type": currentType, "data": trans});
                            });
                            $scope.expressionData = resultArray;
                        }
                    }
                    getPrototypeByMaster(checked, "-1", true)
                    $rootScope.hidePanelLoading();
                }
            });
        };

        function getPrototypeByMaster(checked, reqId, status, isCompare) {
            $scope.isOnline = checked;
            if (!self.reqId) {
                return false;
            }
            $rootScope.showPanelLoading();
            var url = matrix_product_url + "/feature/getFeature?id=" + self.featureId + "&reqId=-1&withAttr=1";
            if (self.sys) {
                url = url + "&sys=" + self.sys;
            }
            $.ajax({
                type: "get",
                url: url,
                async: false,
                success: function (result) {
                    if (result.code == "0") {
                        if (result.data[0].attr != null) {
                            $scope.showUsedTitle = false;
                            $scope.master = result.data[0].attr;
                            if ($scope.master.version != undefined && $scope.prototypeContent.version != undefined) {
                                if(!isCompare) {
                                    $scope.showUsedTitle = $scope.master.version == $scope.prototypeContent.master_version ? false : true;
                                }
                            }
                            if ($stateParams.reqId == "-1") {
                                $scope.showUsedTitle = false;
                            } else {
                                if(!isCompare) {
                                    if ($scope.prototypeContent.prototype == "") {
                                        $scope.prototypeContent.prototype = $scope.master.prototype;
                                    }
                                }
                            }
                            if (!status) {
                                if(!isCompare) {
                                    $scope.prototypeContent = result.data[0].attr;
                                } else {
                                    $scope.prototypeContentMaster = result.data[0].attr;
                                }
                                $scope.$broadcast("to-wsying", result.data[0].attr);
                            }
                        } else {
                            if(!isCompare) {
                                $scope.master = $scope.initPrototype;
                            }
                        }
                    } else {
                        $rootScope.showMessage("error", "失败", result.desc);
                    }
                    $rootScope.hidePanelLoading();
                }
            });
        };

        //根据reqId获取已关联的feature列表
        function getFeaturesByReqId() {
            $rootScope.showPanelLoading();
            var reqId = $stateParams.reqId ? $stateParams.reqId : self.reqId;
            var url = matrix_product_url + "/feature/getAllFeatureForReq?reqId=" + reqId;
            $http.get(url).success(function (result) {
                if (result.code == "0") {
                    for (var i = 0; i < result.data.length; i++) {
                        if (result.data[i].id == self.featureId) {
                            $scope.showEditTitle = false;
                            $scope.showSwitch = true;
                            $scope.isOnline = false;
                            $scope.editHtml = true;
                            getReqName($scope.master.req_snapshot);
                            break;
                        } else {
                            $scope.showEditTitle = true;
                            $scope.showSwitch = false;
                            $scope.isOnline = true;
                            $scope.editHtml = false;
                        }
                    }
                    if(self.readonly) {
                        $scope.isOnline = false;
                        $scope.editHtml = false;
                    }
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
                $rootScope.hidePanelLoading();
            });
        };

        //解决冲突
        $scope.resolveReq = function () {
            var confirmParams = {
                "titleData": "提示",
                "bodyData": "确定要操作吗？"
            };
            $rootScope.confirmWindow(confirmParams, function (data) {
                if (data) {
                    var attrData = $scope.prototypeContent;
                    attrData.master_version = $scope.master.version;
                    attrData.req_snapshot = $scope.master.req_snapshot;
                    var postParams = {
                        id: self.featureId,
                        attr: attrData,
                        reqId: $stateParams.reqId
                    };
                    var url = matrix_product_url + "/feature/updateFeatureAttrForReq";
                    $http({
                        method: "post",
                        url: url,
                        data: JSON.stringify(postParams),
                        headers: {"Content-Type": "application/json"}
                    }).success(function (result) {
                        if (result.code == "0") {
                            $rootScope.showMessage("success", "成功", "解决冲突成功！");
                            $scope.showUsedTitle = false;
                        } else {
                            $rootScope.showMessage("error", "失败", result.desc);
                        }
                    });
                }
            });
        };

        //查询当前节点已被关联的reqName
        function getReqName(name) {
            $rootScope.showPanelLoading();
            var url = matrix_product_url + '/brdRequirement/getBrdRequirements?reqId=' + (name ? name : self.reqId);
            $http.get(url).success(function (result) {
                if (result.code == "0") {
                    if (result.data.length != 0 && result.data != undefined) {
                        $scope.reqName = result.data[0].reqName;
                    }
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
                $rootScope.hidePanelLoading();
            });
        };

        $scope.saveBlurData = function (value) {
            if (!_.isEqual(value, $scope.initPrototype.prototype)) {
                updatePrototypeAttr(value);
            }
        }

        function updatePrototypeAttr(value) {
            var reqId = self.panelType == "tree" ? $stateParams.reqId : self.reqId;
            var attrData = {
                prototype: value,
                form: $scope.prototypeContent.form,
                view: $scope.prototypeContent.view,
                patternType: "doc"
            };
            var postParams = {
                id: self.featureId,
                reqId: reqId,
                attr: attrData
            };
            if ($stateParams.reqId == "-1") {
                var postMasterParmas = {
                    id: self.featureId,
                    attr: attrData,
                    featureName: "页面"
                };
            }
            //$rootScope.showPanelLoading();
            var url = matrix_product_url + "/feature/" + ($stateParams.reqId == "-1" ? "updateFeature" : "updateFeatureAttrForReq");
            $http({
                method: "post",
                url: url,
                data: JSON.stringify($stateParams.reqId == "-1" ? postMasterParmas : postParams),
                headers: {"Content-Type": "application/json"}
            }).success(function (result) {
                if (result.code == "0") {
                    $scope.prototypeContent = $stateParams.reqId == "-1" ? postMasterParmas.attr : postParams.attr;
                    $scope.initPrototype = angular.copy($stateParams.reqId == "-1" ? postMasterParmas.attr : postParams.attr);
                    var currentReqId = $stateParams.reqId == undefined ? self.reqId : $stateParams.reqId;
                    getPrototypeByReq(false, currentReqId);
                    getPrototypeByMaster(false, "-1", true);
                    $scope.$emit('getFeaturesByReq', '');
                    $rootScope.showMessage("success", "成功", "数据修改成功！");
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
                //$rootScope.hidePanelLoading();
            });
        };

        //获取transform数据
        $scope.updateTransformValue = function (type) {
            if (type == "form") {
                if (!_.isEqual($scope.prototypeContent.form, $scope.initPrototype.form)) {
                    if ($scope.prototypeContent.form.split("|")[1]) {
                        $scope.transformTypeForm = $scope.prototypeContent.form.split("|")[0];
                    } else {
                        $scope.transformTypeForm = "text";
                    }
                    updatePrototypeAttr($scope.prototypeContent.prototype);
                }
            } else {
                var splitByEnd = $scope.prototypeContent.view.split("End\n");
                var resultArray = [];
                angular.forEach(splitByEnd, function (trans, index) {
                    resultArray.push({"type": trans.split("\n")[0], "data": trans});
                });
                $scope.transValue = resultArray;
                $scope.transformTypeView = "data";
                if (!_.isEqual($scope.prototypeContent.view, $scope.initPrototype.view)) {
                    // if($scope.prototypeContent.view.split("|")[1]) {
                    //     $scope.transformTypeView = $scope.prototypeContent.view.split("|")[0];
                    // } else {
                    //     $scope.transformTypeView = "text";
                    // }
                    updatePrototypeAttr($scope.prototypeContent.prototype);
                }
            }
        };

        //点击转换后的样式
        $scope.clickTransform = function (type) {
            if (type == "form") {
                $scope.transformTypeForm = "text";
            } else {
                $scope.transformTypeView = "text";
            }
        };

        //修改方法
        function editFeature() {
            $rootScope.showPanelLoading();
            var url = matrix_product_url + '/feature/featureOccupy?reqId=' + $stateParams.reqId + '&id=' + self.selectedBranch.id;
            $http.get(url).success(function (result) {
                if (result.code == "0") {
                    $scope.showSwitch = true;
                    $scope.classStyle = "panel panel-info";
                    $scope.showEditTitle = false;
                    $scope.showUsedTitle = false;
                    $scope.editHtml = true;
                    $scope.isOnline = false;
                    self.selectedBranch.reqId = $stateParams.reqId;
                    var currentReqId = $stateParams.reqId == "-1" ? "-1" : $stateParams.reqId;
                    getPrototypeByReq(false, currentReqId);
                    $scope.$emit('getFeaturesByReq', '');
                    $rootScope.showMessage('success', '成功', '拉取分支成功！');
                } else {
                    $rootScope.showMessage("error", "失败", result.desc);
                }
                $rootScope.hidePanelLoading();
            });
        }

        //声明一个方法（供mFunTree调用）
        $scope.$on('editFeature', function (event, data) {
            editFeature();
        })

        //切换switch，更改isOnline的状态
        $scope.switchChange = function (checked) {
            var reqId = "";
            if (self.panelType == "tree") {
                reqId = checked == true ? "-1" : $stateParams.reqId;
            } else {
                reqId = checked == true ? "-1" : self.reqId;
            }
            checked == true ? getPrototypeByMaster(checked, "-1") : getPrototypeByReq(checked, reqId);
        };

        //切换类型（贴图，Axure，表达式原型）
        $scope.clickGenre = function (genre) {
            $scope.isAxure = genre;
            $scope.genreType =self.mid ? (self.mid + genre) : (self.featureId + genre);
            var axureName = self.mid ? (self.mid +"axure") : (self.featureId +"axure");
            var originId = self.mid || self.featureId;
            if (genre == axureName) {
                if ($scope.prototypeContent.prototype_file_path) {
                    var feaId = self.mid ? self.mid : self.featureId;
                    $("#"+ feaId +"iframepage").remove();
                    setIframe($scope.prototypeContent.prototype_file_path, feaId);
                }
            }
            var oldId = lodash.trim($(".iframClass").attr("id"), "iframepage");
            if(originId != oldId) {
                $(".iframClass").remove();
            }
            var expressionName = self.mid ? (self.mid +"expression") : (self.featureId +"expression");
            if(genre == "expression") {
                if($scope.prototypeContent.expression) {
                    $scope.isSave = true;
                    var splitByEnd = $scope.prototypeContent.expression.split("End\n");
                    var resultArray = [];
                    angular.forEach(splitByEnd, function (trans, index) {
                        var currentType = lodash.trim(trans.split("\n")[0]);
                        if (currentType != "tab-table" && currentType != "form" && currentType != "text-form" && currentType != "flow" && currentType != "table") {
                            currentType = "other";
                        }
                        resultArray.push({"type": currentType, "data": trans});
                    });
                    $scope.expressionData = resultArray;
                } else {
                    $scope.expressionData = null;
                }
            }
        };

        //切换状态（当前，线上，对比）
        $scope.clickStatus = function (status) {
            var reqId = self.panelType == "tree" ? $stateParams.reqId : self.reqId;
            switch(status) {
                case "current": 
                    $scope.onlineIframe = false;
                    $scope.isCompare = false;
                    getPrototypeByReq(false, reqId, true);
                    $scope.isSave = true;
                    if($scope.isAxure == "axure") {
                        $scope.genreType = $scope.feaId +"axure";
                    }
                    if($scope.isAxure == "expression") {
                        $scope.genreType = $scope.feaId +"expression";
                    }
                    if($scope.prototypeContent.expression) {
                        var splitByEnd = $scope.prototypeContent.expression.split("End\n");
                        var resultArray = [];
                        angular.forEach(splitByEnd, function (trans, index) {
                            var currentType = lodash.trim(trans.split("\n")[0]);
                            if (currentType != "tab-table" && currentType != "form" && currentType != "text-form" && currentType != "flow" && currentType != "table") {
                                currentType = "other";
                            }
                            resultArray.push({"type": currentType, "data": trans});
                        });
                        $scope.expressionData = resultArray;
                    } else {
                        $scope.expressionData = null;
                    }
                    $("#"+ $scope.feaId +"iframepage").remove();
                    if($scope.prototypeContent.prototype_file_path) {
                        setIframe($scope.prototypeContent.prototype_file_path, $scope.feaId);
                    }
                    break;
                case "online": 
                    $scope.onlineIframe = true;
                    $scope.isCompare = false;
                    getPrototypeByMaster(true, "-1", false, true);
                    if($scope.isAxure == "axure") {
                        $scope.genreType = $scope.feaId +"axure";
                    }
                    if($scope.isAxure == "expression") {
                        $scope.genreType = $scope.feaId +"expression";
                    }
                    $scope.isSave = true;
                    if($scope.prototypeContentMaster.expression) {
                        var splitByEnd = $scope.prototypeContentMaster.expression.split("End\n");
                        var resultArray = [];
                        angular.forEach(splitByEnd, function (trans, index) {
                            var currentType = lodash.trim(trans.split("\n")[0]);
                            if (currentType != "tab-table" && currentType != "form" && currentType != "text-form" && currentType != "flow" && currentType != "table") {
                                currentType = "other";
                            }
                            resultArray.push({"type": currentType, "data": trans});
                        });
                        $scope.expressionMasterData = resultArray;
                    } else {
                        $scope.expressionMasterData = null;
                    }
                    $("#"+ $scope.feaId +"iframepage").remove();
                    $("#iframepage").remove();
                    if($scope.prototypeContentMaster.prototype_file_path) {
                        setIframe($scope.prototypeContentMaster.prototype_file_path, $scope.feaId);
                    }
                    break;
                case "compare":
                    $scope.onlineIframe = true;
                    $scope.isCompare = true;
                    getPrototypeByReq(false, reqId, true);
                    getPrototypeByMaster(true, "-1", false, true);
                    $("#"+ $scope.feaId +"iframepage").remove();
                    if($scope.prototypeContent.prototype_file_path) {
                        setIframe($scope.prototypeContent.prototype_file_path);
                    }
                    if($scope.prototypeContentMaster.prototype_file_path) {
                        setIframe($scope.prototypeContentMaster.prototype_file_path, $scope.feaId, ("#"+ $scope.feaId +"col-iframe-master"));
                    }
                    if($scope.isAxure == "axure") {
                        $scope.genreType = $scope.feaId +"axure";
                    }
                    if($scope.isAxure == "expression") {
                        $scope.genreType = $scope.feaId +"expression";
                    }
                    $scope.isSave = true;
                    if($scope.prototypeContent.expression) {
                        var splitByEnd = $scope.prototypeContent.expression.split("End\n");
                        var resultArray = [];
                        angular.forEach(splitByEnd, function (trans, index) {
                            var currentType = lodash.trim(trans.split("\n")[0]);
                            if (currentType != "tab-table" && currentType != "form" && currentType != "text-form" && currentType != "flow" && currentType != "table") {
                                currentType = "other";
                            }
                            resultArray.push({"type": currentType, "data": trans});
                        });
                        $scope.expressionData = resultArray;
                    } else {
                        $scope.expressionData = null;
                    }
                    if($scope.prototypeContentMaster.expression) {
                        var splitByEnd = $scope.prototypeContentMaster.expression.split("End\n");
                        var resultArray = [];
                        angular.forEach(splitByEnd, function (trans, index) {
                            var currentType = lodash.trim(trans.split("\n")[0]);
                            if (currentType != "tab-table" && currentType != "form" && currentType != "text-form" && currentType != "flow" && currentType != "table") {
                                currentType = "other";
                            }
                            resultArray.push({"type": currentType, "data": trans});
                        });
                        $scope.expressionMasterData = resultArray;
                    } else {
                        $scope.expressionMasterData = null;
                    }
                    break;
            }
        };

        //上传Axure
        $("#uploadfile").fileinput({
            language: 'zh',       //设置语言
            uploadUrl: matrix_product_url + '/feature/uploadPrototypeFile',
            showPreview: false,  //是否显示预览
            allowedFileExtensions: ["zip"],
            uploadAsync: false,
            uploadExtraData: function () {
                var postParams = {
                    reqId: $stateParams.reqId ? $stateParams.reqId : self.reqId,
                    featureId: $scope.featureId,
                    patternType: "axure"
                };
                return postParams;
            }
        }).on("filebatchuploadsuccess", function (event, data) {
            if (data.response.code == "0") {
                document.getElementById("alertMsg").style.display = 'none';
                document.getElementById("alertMsg2").style.display = 'none';
                $scope.prototypeContent.prototype_file_path = data.response.data;
                $("#iframepage").remove();
                setIframe(data.response.data, $scope.featureId);
            } else {
                if($(".file-caption-name").html() == "") {
                    document.getElementById("alertMsg").style.display = 'none';
                } else {
                    document.getElementById("alertMsg").style.display = 'inline-block';
                }
                return false;
            }
        }).on('fileerror', function (event, data, msg) {  //一个文件上传失败
            console.log('文件上传失败！' + msg);
        });

        $(".fileinput-upload-button").on("click", function() {
            document.getElementById("alertMsg").style.display = 'none';
            if($(".file-caption-name").html() == "") {
                document.getElementById("alertMsg2").style.display = 'inline-block';
                return false;
            }
        });

        $(".fileinput-remove-button").on("click", function() {
            document.getElementById("alertMsg").style.display = 'none';
            document.getElementById("alertMsg2").style.display = 'none';
        });

        //设置iframe
        function setIframe(ifram_path, featureId, masterId) {
            $("#"+ featureId +"iframepage").remove();
            $("#iframepage").remove();
            var iframeId = featureId ? (featureId + "iframepage") : "iframepage";
            $(".down-file-btn").css("display", "block");
            // $(".mm-loading-icon").css("display", "block");
            var date = new Date();
            var url = axure_prototype_url + ifram_path + "index.html?d="+ Date.parse(date);
            var iframe = $("<iframe id='"+iframeId+"' class='iframClass' frameborder='0' scrolling='auto' marginheight='0' marginwidth='0' style='width: 100%;height:100%;transform: scale(" + $scope.scale + ");transform-origin: 0 0;'>");
            iframe.attr('src', url);
            iframe.load(function () {
                // $(".mm-loading-icon").css("display", "none");
            });

            if(masterId) {
                $("#"+ featureId +"iframepage").remove();
                $(masterId).append(iframe);
            } else {
                var colIframeId = featureId ? featureId + "col-iframe" : "col-iframe";
                $scope.colFrameId = colIframeId;

                $timeout(function() {
                    $("#"+ iframeId).remove();
                    $('#'+ colIframeId).append(iframe);
                }, 500);
            }
        };      

        //放大
        $scope.iframePlus = function () {
            if ($scope.scale < 1) {
                $scope.scale += 0.1;
                $("#iframepage").css("transform", "scale(" + $scope.scale + ")");
            }
        };

        //缩小
        $scope.iframeMinus = function () {
            if ($scope.scale > 0.1) {
                $scope.scale -= 0.1;
                $("#iframepage").css("transform", "scale(" + $scope.scale + ")");
            }

        };

        //下载
        $scope.downFile = function() {
            var url = matrix_product_url +"/feature/getPrototypeFile?reqId="+ $stateParams.reqId +"&featureId="+ self.selectedBranch.id;
            window.location.href = url;
        };

        //保存原型表达式
        $scope.saveExpression = function() {
            if($scope.info.expression == "") {
                $rootScope.toasterErrorInfo("数据不能为空！");
                return false;
            }
            $scope.isSave = true;

            var splitByEnd = $scope.info.expression.split("End\n");
            var resultArray = [];
            angular.forEach(splitByEnd, function (trans, index) {
                var currentType = lodash.trim(trans.split("\n")[0]);
                if (currentType != "tab-table" && currentType != "form" && currentType != "text-form" && currentType != "flow" && currentType != "table") {
                    currentType = "other";
                }
                resultArray.push({"type": currentType, "data": trans});
            });
            $scope.expressionData = resultArray;
            var url = matrix_product_url +"/feature/"+ ($stateParams.reqId == "-1" ? "updateFeature" : "updateFeatureAttrForReq");
            var attrData = $scope.prototypeContent;
            attrData.expression = $scope.info.expression;
            attrData.patternType = "expression";
            var postParams = {
                id: self.featureId,
                attr: attrData,
                reqId: $stateParams.reqId
            };
            if ($stateParams.reqId == "-1") {
                var postMasterParmas = {
                    id: self.featureId,
                    attr: attrData,
                    featureName: "页面"
                };
            }
            $http({
                method: "post",
                url: url,
                data: JSON.stringify($stateParams.reqId == "-1" ? postMasterParmas : postParams),
                headers: {"Content-Type": "application/json"}
            }).success(function (result) {
                if (result.code == "0") {
                    $rootScope.toasterSuccessInfo("数据保存成功！");
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
            });
        };

        //编辑原型表达式
        $scope.editExpression = function() {
            $scope.isSave = false;
        };

        $scope.cancelExpression = function() {
            $scope.isSave = true;
        };

        $scope.clearExpression = function() {
            $scope.info.expression = "";
        };

        $scope.sltExpression = function(selectedItem) {
            // $scope.info.expression = "";
            switch(selectedItem) {
                case "table": 
                    $scope.info.expression += $scope.info.tableContent;
                    break;
                case "tab-table": 
                    $scope.info.expression += $scope.info.tabTableContent;
                    break;
                case "form": 
                    $scope.info.expression += $scope.info.formContent;
                    break;
                case "text-form": 
                    $scope.info.expression += $scope.info.textFormContent;
                    break;
                case "flow": 
                    $scope.info.expression += $scope.info.flowContent;
                    break;
                case "form-tab-table": 
                    $scope.info.expression += $scope.info.comboContent;
                    break;
            }
        }
    }
});